package com.example.demo22;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MySaxHandler extends DefaultHandler {
    private String nodeName;
    private StringBuilder title;
    private StringBuilder content;
    private List<HashMap<String,String>> news;

    public List<HashMap<String, String>> getNews() {
        return news;
    }

    /**
     * 开始解析时调用
     * @throws SAXException
     */
    @Override
    public void startDocument() throws SAXException {
        news=new ArrayList<>();
        title=new StringBuilder();
        content=new StringBuilder();
    }

    /**
     * 开始解析某个节点时调用
     * @param uri
     * @param localName 节点名
     * @param qName
     * @param attributes
     * @throws SAXException
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        //记录当前节点名
        nodeName=localName;
    }

    /**
     * 获取节点内容时调用
     * @param ch
     * @param start
     * @param length
     * @throws SAXException
     */
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        //判断并获取节点内容
        if ("title".equals(nodeName)) {
            title.append(ch,start,length);
        }else if ("content".equals(nodeName)){
            content.append(ch,start,length);
        }

    }

    /**
     * 完成解析时调用
     * @throws SAXException
     */
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();

    }

    /**
     * 完成节点解析时调用
     * @param uri
     * @param localName 当前节点名
     * @param qName
     * @throws SAXException
     */
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        //当前节点解析完成时存入数据
        if ("news".equals(localName)) {
            HashMap<String,String> getNews=new HashMap<>();
            getNews.put(title.toString().trim(),content.toString().trim());
            news.add(getNews);
            //清空数据
            title.setLength(0);
            content.setLength(0);
        }
    }
}
